from flask import current_app, jsonify
from flask import render_template
from flask import request
from info.models import Product
from info.tools.response_code import RET
from . import product_blu


@product_blu.route('/')
def product_centre():
    # 1. 获取参数
    req = request.args

    page = req.get('page', '1')
    per_page = req.get('per_page', '20')

    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')

    try:
        news = Product.query.paginate(page, per_page, False)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    # 取到当前页的数据
    news_model_list = news.items  # 当前页的数据
    total_page = news.pages  # 总页数
    current_page = news.page  # 当前页数

    if not news_model_list:
        return jsonify(errno=RET.NODATA, errmsg='当前分类下无数据')

    new_list = []
    for new in news_model_list:
        new_list.append(new.to_dict())

    data = {
        'total_page': total_page,
        'current_page': current_page,
        'Product_list': new_list
    }

    if page != 1:
        return jsonify(errno=RET.OK, errmsg='数据请求成功', data=data)

    return render_template("products.html", data=data)
